import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { IUserInfo, IMenus } from '@/api/types/common'
import { setItem, getItem } from '@/utils/storage'
import { USER, MENUS } from '@/utils/constants'

const state = {
  isCollapse: false,
  user: getItem<{token: string} & IUserInfo>(USER), // 将token和IUserInfo合并
  menus: getItem<IMenus[]>(MENUS)
}
// 使用typeof推导ts类型
export type State = typeof state

export const key: InjectionKey<Store<State>> = Symbol('store')
// 创建一个新的 store 实例
export const store = createStore<State>({
  state,
  mutations: {
    setIsCollapse (state, payload: boolean) {
      state.isCollapse = payload
    },
    setUser (state, payload) {
      state.user = payload
      setItem(USER, state.user)
    },
    setMenus (state, payload) {
      state.menus = payload
      setItem(MENUS, payload)
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
